ts = require("ts")
init(1)
local ts = require("ts")
local json = ts.json
require('TSLib')
--require("dataa")
--require("基本功能")
local sz = require("sz")
local json = sz.json
local socket = require ("socket");
local http = require("szocket.http")
local mime = require("mime")


local filepath = "/sdcard/360ex/ai.png" 		-- 打码识别图片
local picpath = "/sdcard/360ex/" 				-- 图片根目录
local datu_num = 0								-- 记录识别到的打图次数
local one_ocr_datu_num = 0						-- 第一个强
local g验证密码	= "123456"
local g服务器ip = "http://3dg7wj531797.vicp.fun"
-- local g服务器ip = "http://127.0.0.1:"
local JTLJ=userPath().."/res/yzm.png"
AUTH_KEY = "74KCAWQ7JNCF3KVBUMHA"
time = 0
-- 请自行修改自己的图片路径
--image_dir = "/sdcard/Pictures/"
image_dir = "/mnt/sdcard/TouchSprite/res/"

YZTZ={
    ["成语"]={0xffff01, "-2|13|0xddde04,-6|23|0xfdfd01,-1|26|0xffff01,18|26|0xffff01,18|16|0xffff01,18|3|0xffff01,15|-5|0xffff01,23|-5|0xffff01", 90, 558, 147, 599, 188};
    ["漂浮字"]={0xf4f4f4, "0|9|0xffffff,3|28|0xffffff,10|27|0xffffff,18|-1|0xffffff,18|14|0xf9f9f9,27|15|0xffffff,27|27|0xfcfcfc,10|26|0xffffff,19|19|0xebecec", 90, 374, 148, 1384, 732};
    ["漂浮表情"]={};
    ["四小人"]={0xf1f2f1, "2|11|0xf2f3f2,13|17|0xf4f4f4,40|6|0xfefefe,56|6|0xfefefe,122|15|0xf5f5f5,156|0|0xfb0101,179|13|0xf60202,9|13|0xfbfbfb", 90, 326, 60, 1318, 410};
}

tz={
    ["口袋"]={0xf8cdcf, "11|-16|0xf8c7c7,-7|-23|0xf8dcd8,4|-42|0x30ac18,-9|-49|0x057310,0|-60|0xdcba96,-18|-63|0xdfcfa0,-32|-65|0xd6d074,-44|-62|0x1c502a,-46|-48|0xe6a1b7", 90, 373, 6, 548, 175};
}
function 报警()

    local 超时 = os.time()
    local tms = nil
    if UI_msg == "震动提示" then
        repeat
            mSleep(math.random(300,500))
            mSleep(yanchi*1000)
            vibrator()				   --振动
            if os.time() - 超时 > 300 then

                closeApp("com.netease.mhxyhtb")
                dialog("验证处理失败,等待手动处理超过5分钟,自动关闭游戏！", time)
                lua_exit()
                mSleep(10)
            end
        until (_cmp_tb(Color['主界面']))
    else
        local tms = nil
        repeat
            if tms == nil or os.time() - tms > 30 then
                if UI_lings=="铃声_Msg" then
                    nLog('播放铃声')
                    playAudio("msg.mp3")
                elseif UI_lings=="铃声_BJ" then
                    playAudio("GameGX.mp3")

                elseif UI_lings=="铃声女声" then
                    playAudio("GameBJ.mp3")
                end
                mSleep(math.random(500,800))
                mSleep(1000)
                tm = os.time()
            end
            if os.time() - 超时 > 300 then
                closeApp("com.netease.mhxyhtb")
                dialog("验证处理失败,等待手动处理超过5分钟,自动关闭游戏！", time)
                lua_exit()
                mSleep(10)
            end
            mSleep(math.random(300,500))
            mSleep(1000)
        until (_cmp_tb(Color['主界面']))
        playAudio("")
    end

end

function JClick(x,y,f)
    local M=10
    nLog('点击了'..x..','..y)
    local f=f or 2
    if DeBug=='true' then fwShowWnd("DeBugWid",x-M,y-M,x+M,y+M,1)	 end
    touchDown(x, y);
    if DeBug=='true' then fwShowTextView("DeBugWid","Id2"," ","center","ff0000","ff0000",15,0,1,1,19,19)  end
    mSleep(math.random(30,60));
    touchUp(math.random(x-f,x+f), math.random(y-f,y+f));
    mSleep(math.random(30,60));
    if DeBug=='true' then fwCloseWnd("DeBugWid") end
end

function FWClick(table,cs)
    local cs=cs or 1
    if type(table) ~= 'table' then
        return
    end
    for var=1,cs do
        JClick(math.random(table[1],table[3]),math.random(table[2],table[4]))
        mSleep(math.random(20,50))
    end
end

function Click(x,y,cs,f)  --
    local cs=cs or 1
    for var=1,cs do
        JClick(x,y,f)
        mSleep(math.random(20,50))
    end
end


function GetColor(color,jd,fw)--找特征 ，  特征，精度，范围
    local jd=jd or color[3]
    local fw=fw or {color[4],color[5],color[6],color[7]}
    local x,y = findMultiColorInRegionFuzzy(color[1], color[2], jd, fw[1],fw[2],fw[3],fw[4])
    if x ~= -1 and y ~= -1 then
        return true,x,y
    else
        return false,x,y
    end
end


function ReadFileByte(file)
    local f = io.open(file,"rb")
    local retbyte = f:read("*all")
    f:close()
    return retbyte
end



local port = {		-- 端口池
    ['朝向'] = {{"",1},{"",0}},
    ['成语'] = {{"",1},{"",0}},
    ['漂浮'] = {{"6008",1},{"7006",0}},
    ['朝向2'] = {{"",1},{"",0}},
}

--CARD_NUM='SBUHDNZEMFL8DSQ9PW7K'
function 获取端口(model)
    local min_value = port[model][1][2] -- 假设第一个为最小值
    local min_prot = port[model][1][1]  -- 假设第一个为最小值的端口
    local min_index = 1
    for i = 2,#port[model] do
        if port[model][i][2] < min_value then
            min_value = port[model][i][2]
            min_prot =  port[model][i][1]
            min_index = i
        end
    end
    port[model][min_index][2] = port[model][min_index][2] + 1
    return min_prot
end

function 服务器验证(model)
    local _path=userPath().."/res/yzm.png"
    local err_num = 0
    err_num = err_num + 1
    -- >>>>>>>>>>>>>>>>>>>>> 	组包
    local url = g服务器ip
    local ju_port = 获取端口(model)
    url = url .. ju_port .. "/ocr?time="
    local t_time = tostring(os.time())
    local t_sign = g验证密码..t_time

    url = url .. t_time .. "&sign=" .. t_sign:md5()
    nLog(url)
    local FileByte = ReadFileByte(_path)
    local options = {
        ["tstab"] = 1, -- 必填项
        ["timeOut"] = 30,
        ["urlEnCode"] = false
    }
    local json_string = cjson.encode(options)

    nLog(url)
    nLog(cjson.encode(FileByte))
    nLog(cjson.encode(options))
    local str = httpPost(url,FileByte,options)
    if str == false then
        nLog("验证失败")
        return false
    elseif string.sub(str,1,2) == "-1" then
        nLog("验证失败")
        if model == "漂浮" then
            return false,string.sub(str,4,-1)
        else
            return false
        end
    else
        nLog("验证成功")
        if model == "漂浮" then
            local str1 = urlDecoder(str)
            local arr = strSplit(str1,"|")
            return arr[1],arr[2]
        else
            return urlDecoder(str)
        end
    end
end

function 四小人()
    --------------------------
    local count=0
    local n,nn=0,0;
    local err_num = 0 		-- 如果重复太多次,没成功就直接报警
    local 超时 = os.time()
    while count<20 do
        if os.time() - 超时 > 55 then
            if UI_DAMA=="双重打码"then
                _验证.四小人()
                --	战斗计时=os.time()
                return
            end
            return
        end
        if _cmp(Color['验证']['地图不存在']) then
            return
        end
        if n==0 then
            local bool,x,y=_find_tb(Color['验证']['朝向面2'])  --local bool,x,y=_find_tb(Color['验证']['朝向择'])
            if bool then
                nLog('面'..x..','..y)
                if nn<3 then
                    n=1;
                    nLog("四小人验证")
                    nLog('朝向面'..x..','..y)
                else
                    return;
                end
            end
        elseif n==1 then
            local bool,x,y=_find_tb(Color['验证']['朝向面1'])
            if bool then
                local ret = ""
                --snapshot(JTLJ,x-68,y+66,x+803,y+315)  --截图
                snapshot(JTLJ,x-114,y+84,x+726,y+369)  --截图
                --			snapshot(JTLJ,600,287,1452,580)
                if err_num >= 2 then	-- 主服务器识别2次,使用次服务器识别
                    ret = 服务器验证("朝向2")
                else
                    ret = 服务器验证("朝向")
                end
                if ret then
                    local arr = strSplit(ret,",")
                    Click(arr[1] + (x-114),arr[2]+(y + 84))
                    nLog("四小人：点击：" .. (arr[1] + (x-114)) .. "," .. (arr[2]+(y + 84)))
                    mSleep(500)
                end
            end
            n=0;
            nn=nn+1;
            err_num=err_num+1
        end
        count=count+1
    end
end


function 成语识别处理(str,CY)--CY 传入识别第几个字
    local arr = strSplit(str,"|")
    local ret = {}
    local 成语=string.gsub(arr[5],"=","")
    成语 = { string.sub(成语,1,3),string.sub(成语,4,6),string.sub(成语,7,9),string.sub(成语,10,12) }
    for i=1,#arr do
        arr[i]=strSplit( arr[i],",")
        if arr[i][3]==成语[CY] then
            nLog("arr["..i.."][3]="..arr[i][3])
            mSleep(888)
            Click(tonumber(arr[i][1])+553,tonumber(arr[i][2])+314)---点击成语
        return;
        end
    end
end


---改
function 成语验证()
    nLog(url)
    local err_num = 0
    local n,nn,nnn,cishu=0,0,0,0
    local i=1
    local 超时 = os.time()
    while (true) do
        if n==0 then
            if GetColor(tz['口袋']) then return end
            if GetColor(YZTZ['成语']) then
                if nnn<4 then
                    nLog("开始验证成语")
                    -- scrnLog("开始验证成语")
                    n=1
                else
                    --报警(5000)
                    dialog('手动输入')
                    nLog("验证失败次数过多，手动验证")
                end
            else
                return
            end
        elseif n==1 then
            snapshot(JTLJ, 553, 314, 1027, 485)			-- 截取成语识别范围图片
            local ret = 服务器验证("成语")
            if ret then
                成语识别处理(ret,i)
                mSleep(1500)
                i=i+1;
                nLog('点击了'..i..'次',1)
            else
                nn=nn+1
                if nn>2 then
                    FWClick({794, 686, 890, 714})
                    mSleep(500)
                    nLog("重置成语重新验证！")
                    err_num=err_num+1
                    nLog('err_num重置'..err_num..'次')
                    if UI_备用图灵打码=="备用图灵打码" then
                        nLog('确定失败__开始调用图灵打码.............')
                        图灵成语(mima)
                        return
                    else
                        -- 	报警('成语重新验证')
                    end
                    n,nn=0,0
                end
            end
            if i>4 then
                n=2
            end
        elseif n==2 then
            nnn=nnn+1;
            --		scrnLog('点击了确认按钮'..nnn..'次')
            ------------------
            FWClick({1205, 685, 1285, 720})
            mSleep(800)
            nLog('点击了确认按钮'..nnn..'次')
            if nnn>=2 then
                --dialog('图片识别错误，请手动完成验证')
                -----------------------
                if UI_备用图灵打码=="备用图灵打码" then
                    nLog('确定失败__开始调用图灵打码.............')
                    图灵成语(mima)
                    return
                else
                    报警('成语重新验证')
                end
            end
            --			closeScrnLog('点击了确认按钮'..nnn..'次')
            for var=1,20 do
                if GetColor(YZTZ['成语']) then
                    break;
                end
                mSleep(100)
            end
            n,nn=0,0
            i=1;
        end
    end
end

function 获取颜色(x,y)
    -- 获取返回的坐标,附近10x10的颜色
    local temp = {getColor(x, y),x,y}
    if not(temp[1] > 0x7086ba) then -- 如果返回的坐标颜色 > 0x7086ba,那么不用遍历了,直接查找这个颜色
        local list = {}
        for i = 1,10 do
            list[#list+1] = {getColor(x, y + i),x,y + i}	-- 下面
            list[#list+1] = {getColor(x, y - i),x,y - i} -- 上面
            list[#list+1] = {getColor(x + i, y),x + i, y} -- 右边
            list[#list+1] = {getColor(x - i, y),x - i, y} -- 左边
            list[#list+1] = {getColor(x - i, y - i),x - i, y - i} -- 左上角
            list[#list+1] = {getColor(x + i, y + i),x + i, y + i} -- 右下角
            list[#list+1] = {getColor(x - i, y + i),x - i, y + i} -- 左下角
            list[#list+1] = {getColor(x + i, y - i),x + i, y - i} -- 右上角
        end
        -- 取出周围颜色中的最大值
        table.sort(list,function(a,b)
            return a[1] > b[1]
        end)
        temp = list[1]
    end
    return temp[2],temp[3]
end

---改
function 漂浮()
    local n,nn=0,0;
    while true do
        if n==0 then
            if GetColor(tz['口袋']) then return end
            if GetColor(YZTZ['漂浮字']) then
                if nn<4 then
                    n=1;
                    nLog("开始验证漂浮字")
                    --				scrnLog("开始验证漂浮字")
                else
                    if UI_备用图灵打码=="备用图灵打码" then
                        nLog('确定失败__开始调用图灵打码.............')
                        图灵漂浮字(mima)
                        return
                    else
                        报警('成语重新验证')
                    end

                end
            else
                return;
            end
        elseif n==1 then
            local bool,x,y = GetColor(YZTZ['漂浮字'])
            nLog(x..","..y)
            local x1,y1,x2,y2 = x - 10,y - 40,x + 710,y + 320
            keepScreen(true)
            snapshot(JTLJ, x1,y1,x2,y2)
            local ret =服务器验证("漂浮")
            if ret then
                local arr = strSplit(ret,",")
                for i=1,#arr do
                    nLog(arr[i])
                end
                arr[1],arr[2] = tonumber(arr[1]) + x1,tonumber(arr[2]) + y1
                local x,y = 获取颜色(tonumber(arr[1]),tonumber(arr[2]))
                --dialog('357'..x..','..y)
                snapshot(JTLJ ,x - 5, y - 5,x + 5, y + 5)
                keepScreen(false)
                for i = 1,10 do
                    x, y = findImageInRegionFuzzy(JTLJ, 85, x1,y1,x2,y2,0);
                    if x > -1 then
                        nLog("漂浮字点击"..x..","..y)
                        Click(x,y,3)
                    end
                    mSleep(200)
                end
            else
                nLog("服务器验证失败")
                keepScreen(false)
            end
            n=0;
            nn=nn+1;
        end
    end
end

成语验证()
-- 漂浮()
lua_exit()